Description:
C#
provides the foreach
construction for enumerating collection members
and allows the programmer to implement their own enumerators.
Usually, it is not possible to update a collection during enumeration.
For example, if you try to update System.Collection.ArrayList
inside of a foreach
body, you will get an InvalidOperationException.
However, the programmer can implement their own enumerators and forget to
check that the collection was not updated. Code that updates a collection during
iteration can work in some cases, but in general, can cause unpredictable behavior.
This audit detects code that attempts to modify a collection inside of a foreach
loop enumerating the
collection. Methods with names containing Delete, Remove, Insert, and Add
are considered to be mutators.
Incorrect:
foreach (Element x in c) {
if (x.Name.Equals(name)) {
c.Remove(x);
}
}
Correct:
ArrayList toBeRemoved = new ArrayList();
foreach (Element x in c) {
if (x.Name.Equals(name)) {
toBeRemoved.Add(x);
}
}
foreach (Element x in toBeRemoved) {
c.Remove(x);
}